<?php
namespace console\controllers; 
use common\models\Balance;
use common\models\BalanceLog;

use common\models\BalanceType;
use common\models\Member;
use common\models\Setting;
use common\models\StaticInstance;
use common\models\TradeCommodity;
use common\models\TradeModel;
use common\models\WithdrawLog;
use common\service\vesrpc\ves;
use Yii;


use common\utils\CommonFun;

use common\bonus\BaseBonus;



/*
	* 静态释放
*/
class ReleaseController extends CoreController
{


	public function actionIndex()
	{
		$where = ['status'=>'1','order_type'=>['1','2','3']];
		/*判断剩余总数*/
		$data = StaticInstance::find()->where($where)->andWhere(['>','remain_num',0])->asarray()->all();

		if(!$data) return false;

		$conf = TradeModel::getStaticReleaseConf('StaticRelease');

		## 帐本分配方式
		$assignType = json_decode($conf['assign_type'],1);

		$st = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$memberId = array_unique(array_column($data,'commodity_id'));
		/**/
        $commodityInfo = TradeCommodity::getAll(['commodity_id'=>$memberId],'day_income,commodity_id');
        $commodity     = [];

        foreach ($commodityInfo as $gk=>$gv) {
            $commodity[$gv['commodity_id']]=$gv['day_income'];
        }

		foreach($data as $val)
		{
		     $state = Member::getOne(['member_id'=>$val['member_id']],'state');
            if ($state==0){
                continue;
            }
            
			$where = ['member_id'=>$val['member_id'],'source_id'=>$val['id'],'source_type'=>8];
//			if(BalanceLog::find()->where($where)->andWhere(['>=','create_time',$st])->count()) continue;

			/*求出每天释放的金额数量*/
			$bonus = $this->getBonus($conf,$val,$commodity);

			if($bonus<=0) continue;
			//封顶值
//			if($conf['max_times']>0 && $val['was_num']>=$val['in_num']*$conf['max_times']) continue;


			## 更新实例
			$bonus = $this->updateInstance($val,$bonus);


			foreach($assignType as $btype=>$rate)
			{
				$balance = round($bonus * $rate / 100 , 2);
				//加入到账本
				$res = Balance::addBalance($val['member_id'],$btype,$balance,8,$val['id']);

				if(!$res['state']){
					$str = '静态释放 instance_id:'.$val['id']."\r\n conf:".json_encode($conf).'msg:'.$res['msg'];
					CommonFun::writeLog($str,'bonus');
				}
			}
            $Static = StaticInstance::findOne(['id'=>$val['id']]);

            if($Static->bonus_day==$Static->period_day)
            {
                //合约到期，进行解约操作，挂卖UPH
//                $res = Balance::addBalance($val['member_id'],1,$val['in_num'],16,$val['id']);
//                if(!$res['state']){
//                    $str = '增加合同本金失败';
//                    CommonFun::writeLog($str);
//                }
//                $res = Balance::reduceBalance($val['member_id'],3,$val['in_num'],16,$val['id']);
//                if(!$res['state']){
//                    $str = '释放合同金额失败';
//                    CommonFun::writeLog($str);
//                }
                //UPH价格
                $price = BalanceType::getOne(['type' => 2], ['price'])['price'];//UPH价格
                $taker_fee_rate = 0;
                $maker_fee_rate = 0;
                $source = '';
                try {
                    $transaction = \Yii::$app->db->beginTransaction();
                    //减少钱包UPH余额
                    $res = Balance::transferBalanceToVes($val['member_id'],3,$val['in_num'],23,0,'交易所出售UPH');
                    if(!$res['state'])
                        throw new \Exception($res['msg']);
                    $id = Yii::$app->db->getLastInsertId();
                    //增加交易所UPH余额
                    $data = ves::balance_update($val['member_id'],'UPH','SELLUPH',$id,$val['in_num']);
                    if($data['error'] != null)
                        throw new \Exception($data['error']['message']);
                    $transaction->commit();
                }
                catch (\Exception $exception)
                {
                    $transaction->rollback();
                    continue;
                }
                $data = ves::order_put_limit($val['member_id'],'UPHUSDT',1,$val['in_num'],$price,$taker_fee_rate,$maker_fee_rate,$source);
                if($data['error'] != null){
                    continue;
                }

        }
			if($conf['next_action']>0){
				$member = Member::getMemberById($val['member_id'],['member_name','member_id','member_email']);
				## 触发后续操作
				$params                 = array();
				$params['money']        = $bonus;
				$params['member_id']    = $val['member_id'];
				$params['source_id']    = $val['id'];
				$params['mch_id']       = $val['mch_id'];
				$params['trigger_type'] = $conf['next_action'];
				$params['desc']         = 'from 【'.$member['member_name'].'】';
				$params['category']     = 1;
                $params['model_id']     = 8;

				BaseBonus::bonusRun($params);		
			}

		}
		return true;
	}


	//更新实例
	private function updateInstance($instance,$bonus)
	{
		//因为实例数据已经变化了，需要重新获取，不然会覆盖
		$instance = StaticInstance::find()->where(["id"=>$instance['id']])->andWhere(['>','remain_num',0])->asarray()->one();
		if(!$instance) return false;

		$bonus = min($instance['remain_num'],$bonus);

		$data = array();
		/*已经释放的钱*/
		$data['was_num'] = $instance['was_num'] + $bonus;
		/*释放+1天*/
		$data['bonus_day'] = $instance['bonus_day'] + 1;
		/*剩余总数-当前价格*/
		$data['remain_num'] = $instance['remain_num'] - $bonus;			
		$data['update_time'] = time();
		if($instance['period_day']-$data['bonus_day']<=0) $data['status'] = '2';

		$flag =  StaticInstance::updateAll($data,['id'=>$instance['id']]);
		if(!$flag){
			echo "实例更新失败，id:".$instance['id']."\r\n";
			return false;
		}
		return $bonus;
	}


	private function getBonus($conf,$val,$commodity)
	{


		if($val['bonus_num'] >0 ) return $val['bonus_num'];

		$staticRate = $conf["release_rate"];
		$dynamicRate = $conf["dynamic_rate"];

		## 递减释放
		if($conf['release_type'] == 1)
		{
			if($val['type'] == 1) return $val['remain_num'] * $staticRate / 100;
			if($val['type'] == 2) return $val['remain_num'] * $dynamicRate / 100;
		}

		## 固定值释放
		if($conf['release_type'] == 2)
		{
			if($val['type'] == 1) return $val['total_num'] * $staticRate / 100;
			if($val['type'] == 2) return $val['total_num'] * $dynamicRate / 100;
		}

		if($conf['release_type'] == 3)
		{
			## 这种方式需要根据具体项目处理
			## 1基数递减方式
//			$unit = ceil($val['remain_num']/400);
//			return $unit*400*$staticRate/100;
            //价格不同静态释放金额不同

            return bcmul($val['total_num'],$commodity[$val['commodity_id']],4)/100;
		}
		return 0;
	}



	########## 如果提现到交易所 没有卖出对应比例数量的LCL则需要扣除 释放的 余额
	public function actionCheckSell()
	{
		## 查询昨天提现记录
		$st = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$st = $st - 86400;  
		$data = WithdrawLog::find()->where(['in','state',[2,4]])->andWhere(['>=','create_time',$st])->asarray()->all();
		if(!$data) return true;

		## 钱包地址对应 会员id 的提现数量
		$list = $listTotal = array();
		foreach($data as $val)
		{
			if(isset($list[$val['collect_info']][$val['member_id']]))
				$list[$val['collect_info']][$val['member_id']] += ($val['money'] - $val['service_charge'])/$val['price'];
			else
				$list[$val['collect_info']][$val['member_id']] = ($val['money'] - $val['service_charge'])/$val['price'];

			if(isset($listTotal[$val['collect_info']]))
				$listTotal[$val['collect_info']] += ($val['money'] - $val['service_charge'])/$val['price'];
			else
				$listTotal[$val['collect_info']] = ($val['money'] - $val['service_charge'])/$val['price'];
			
		}

		if(!$list) return false;

		$sellRate = Setting::getValue('trade','sell_rate');
		$price = Setting::getValue('price','lcl');

		foreach($list as $address=>$valArr)
		{
			## 获取 已卖出数量
			$sellCount = $this->getSellCount($address,$st);
			$needSellCount = floor($listTotal[$address]*$sellRate/100);
			if($sellCount>=$needSellCount) continue;

			## 差值
			$diffCount = $needSellCount - $sellCount;
			$diffCount = $diffCount*$price; 

			foreach($valArr as $mid=>$money)
			{
				$nums = round($money/$listTotal[$address]*$diffCount,2);
				if($nums<=0) continue;

				## 记录日志
				CommonFun::writeLog('address:'.$address.'---mid:'.$mid.'---num:'.$nums,'sell_diff');

				## 更新会员表记录
				if(!Member::updateAllCounters(['balance_due'=>$nums],['member_id'=>$mid]))
					CommonFun::writeLog('会员表balance_due更新失败，nums:'.$nums.'--mid:'.$mid,'sell_diff');
			}
		}
	}

	private function getSellCount($address,$date)
	{
		$params = array(
			'address'	=> $address,
			'date'		=> $date, //时间戳
		);
		$url = 'http://prod.api.bitqq.io/api/v1/public/lcl/sell_count';
		$res = $this->post_curl($url,$params);
		CommonFun::writeLog($res,'sell_count');
		CommonFun::writeLog($address,'sell_count');
		$res = json_decode($res,1);
		// var_dump($res);
		if($res['msg']=='success') return $res['count'];
		return 0;
	}



	## 扣除余额 这个最好在释放之后执行
	public function actionAutoReduceBalance()
	{
		$data = Member::find()->select(['member_id','balance_due'])->where(['>','balance_due',0])->asarray()->all();
		if(!$data) return true;

		foreach($data as $val)
		{
			$bInfo = Balance::getBalance($val['member_id'],3);
			$num = min($bInfo['balance'],$val['balance_due']);
			if($num<=0) continue;

			$transaction = Yii::$app->db->beginTransaction();

			## 扣除余额
			$res = Balance::reduceBalance($val['member_id'],3,$num,11,0);

			$flag2 = Member::updateAllCounters(['balance_due'=> -$num],['member_id'=>$val['member_id']]);

			if($res['state'] && $flag2){
				$transaction->commit();
			}else
			{
				$transaction->rollback();
			}
		}
	}



}


